#!/usr/bin/python

import subprocess
import string
import socket
import os
import argparse

# Create the ~/chef-solo/node.json file.
#
# The node.json file contains the machines IP address, the machine ID (a number)
# and the repo server.
#
# If the node is being clustered, the role 'clustered' is added, and after
# clustering the tag 'clustered' is added (for homer/homestead)
#
# The node.json file is templated in lib/node_json_template.

parser = argparse.ArgumentParser()

parser.add_argument('--cluster', action='store_true')
parser.add_argument('--tag', action='store_true')

args = parser.parse_args()

# Populate the dictionary
d = {}

d['LOCAL_IP'] = subprocess.check_output(["unit-get", "private-address"]).rstrip()
d['MACHINE_ID'] = str(int(os.environ['JUJU_UNIT_NAME'].split('/')[1]) + 1)
d['REPO'] = subprocess.check_output(["config-get", "repo"]).rstrip()
d['TRUSTED_PEERS'] = ','.join(['"' + ip + '"' for ip in subprocess.check_output(["config-get", "trusted_peers"]).rstrip().split(',')])

node_file = "/home/ubuntu/chef-solo/node.json"
if args.cluster or (os.path.exists(node_file) and "clustered" in open(node_file).read()):
        d['CLUSTER'] = ",\n    \"role[clustered]\""
        d['CLUSTERED'] = ", \"clustered\""
        d['TAG'] = ""

        if args.tag or (os.path.exists(node_file) and "tags" in open(node_file).read()):
                d['TAG'] = ",\n  \"tags\": [\"clustered\"]"

else:
        d['CLUSTER'] = ""
        d['CLUSTERED'] = ""
        d['TAG'] = ""

# Open template file
charm_dir = os.environ['CHARM_DIR']
with open( '%s/lib/node_json_template' % charm_dir ) as f:
        src = string.Template( f.read() )

# Make the substitutions
result = src.substitute(d)

# Write to ~/chef-solo/node.json
with open('/home/ubuntu/chef-solo/node.json', 'w') as f:
        f.write(result)
